package cz.muni.fi.pb138.mathml_canonicalizator;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @author ndru
 */
public class NodeImpl implements Node {

    private final String tagName;
    
    private List<Node> children = new ArrayList<Node>();
    private Map<String, String> attributes;
    private String textContent = null;
    private boolean shadow = false;

    public NodeImpl(String tagName, Map<String, String> attributes) {
        this.tagName = tagName;
        // FIXME: passing Attributes object instead of a Map might be better
        // (but would create tight coupling with the SAX library)
        this.attributes = attributes == null ? null : new HashMap<String, String>(attributes);

    }

    @Override
    public String getTagName() {
        return tagName;
    }

    @Override
    public String getTextContent() {
        return textContent;
    }

    @Override
    public void setTextContent(String textContent) {
        this.textContent = textContent;
    }

    @Override
    public List<Node> getChildren() {
        return children;
    }

    @Override
    public void addChild(Node child) {
        children.add(child);
    }

    @Override
    public Map<String, String> getAttributes() {
        return attributes;
    }
    
    @Override
    public boolean isShadow() {
        return shadow;
    }
    
    @Override
    public void setShadow(boolean shadow) {
        this.shadow = shadow;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        
        if (!isShadow()) {
            sb.append('<').append(tagName);

            if (attributes != null) {
                for (Map.Entry entry : attributes.entrySet()) {
                    sb.append(' ').append(entry.getKey()).append("=\"").
                            append(entry.getValue()).append('"');
                }
            }
            sb.append('>');

            if (textContent != null) {
                sb.append(textContent);
            }
        }
        
        for (Node ch : children) {
            sb.append(ch);
        }

        if (!isShadow()) {
            sb.append("</").append(tagName).append('>');
        }
        
        return sb.toString();
    }
}
